package com.andy.springboot.controller;

import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;

import com.andy.springboot.dto.ResponseResult;
import com.andy.springboot.dto.ReturnCode;
import com.andy.springboot.exception.ActionException;

/**
 * controller基类
 * @author Andy.ye
 * @date 2018年3月23日 下午3:27:21
 */
public class BaseController {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	protected ResponseResult getResponseResult(ResultDelegate delegate) {
		return getResponseResult(delegate, null);
	}

	protected ResponseResult getResponseResult(ResultDelegate delegate, BindingResult bindingResult) {
		ResponseResult result = new ResponseResult();
		try {
			if (bindingResult != null && bindingResult.hasErrors()) {
				result.setCode(ReturnCode.PARAM_ERROR.getCode());
				result.setMessage(bindingResult.getFieldError().getDefaultMessage());
				result.setData("");
				return result;
			}
			Object resultObject = delegate.getResultObject();
			result.setCode(ReturnCode.SUCCESS.getCode());
			result.setMessage(ReturnCode.SUCCESS.getMessage());
			result.setData(resultObject);
			return result;
		} catch (ActionException e) {
			logger.error(e.getMessage(), e);
			result.setCode(e.getRtnCode().getCode());
			result.setMessage(String.format(e.getRtnCode().getMessage(), e.getPlaceHolder()));
			result.setData("");
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setCode(ReturnCode.UNKNOWN.getCode());
			result.setMessage(ReturnCode.UNKNOWN.getMessage());
			result.setData("");
			return result;
		}
	}

	protected interface ResultDelegate {

		Object getResultObject();
	}

	/**
	 * 获取包含contextName的域名地址，末尾包含"/"
	 * @param request
	 * @return
	 */
	protected static String getBasePath(final HttpServletRequest request, final ServletContext servletContext) {
		StringBuffer url = request.getRequestURL();
		String protoc = request.getHeader("X-Forwarded-Proto");
		if ("https".equalsIgnoreCase(protoc)) {
			int point = url.indexOf("://");
			if (point > 0) {
				url.delete(0, point);
				url.insert(0, "https");
			}
		}
		url = url.delete(url.length() - request.getRequestURI().length(), url.length());
		String contextName = servletContext.getServletContextName();
		if (StringUtils.isNotBlank(contextName) && !"/".equals(contextName)) {
			if (!StringUtils.endsWith(url.toString(), "/") && !StringUtils.startsWith(contextName, "/")) {
				url.append("/");
			}
			url.append(servletContext.getServletContextName());
		}
		if (!StringUtils.endsWith(url.toString(), "/")) {
			url.append("/");
		}
		return url.toString();
	}

	protected Date checkAndParseDate(String dataStr, String pattern) {
		try {
			return DateUtils.parseDate(dataStr, new String[] { pattern });
		} catch (Exception e) {
			throw new ActionException("日期格式不正确！", e);
		}
	}

	protected Date checkAndParseDate(String dataStr) {
		return checkAndParseDate(dataStr, "yyyy-MM-dd");
	}
}
